const express = require('express');
const router = express.Router();
const BookModel = require('../models/BookModel') //看老师路径

// 跳转至商品展示页面
router.get('/list', (req, res) => {
    BookModel.find((error, data) => {
        if (error) {
            res.render('book/error', {errorMsg: '展示商品列表失败'})
        } else {
            res.render('book/list', {books: data})
        }
    })
})
// 进入商品修改页面
router.get('/toUpdate/:id', (req, res) => {
    let {id} = req.params;
    console.log(id);
    BookModel.findOne({_id: id}, (error, data) => {
        if (error) {
            res.render('book/error', {errorMsg: '读取商品列表失败'})
        } else {
            res.render('book/addOrUpdate', {books: data})
        }
    })
})
// 进入商品添加页面
router.get('/toAdd', (req, res) => {
    let books = {
        name: '',
        author: '',
        price: 0
    }
    res.render('book/addOrUpdate', {books})
      
})
// 商品修改路由
router.post('/update', (req, res) => {
    let book = req.body;
    BookModel.updateOne({_id: book._id}, book, (error, data) => {
        if (error) {
            res.render('book/error', {errorMsg: '修改商品内容失败'})
        } else {
            res.redirect('/book/list');
        }
    })
})
// 商品添加路由
router.post('/add', (req, res) => {
    let book = req.body;
    BookModel.create(book, (error, data) => {
        if (error) {
            res.render('book/error', {errorMsg: '添加商品失败'})
        } else {
            res.redirect('/book/list');
        }
    })
})
// 商品删除路由
router.get('/remove/:id', (req, res) => {
    let {id} = req.params;
    BookModel.deleteOne({_id: id}, (error, data) => {
        if (error) {
            res.render('book/error', {errorMsg: '删除商品失败'})
        } else {
            res.redirect('/book/list');
        }
    })
})

// // 测试ejs
// router.get('/list', (req, res) => {
//     res.render('book/list', {})
// })
module.exports = router;